package com.liyongjian.xhban.api;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.liyongjian.xhban.dal.AccountGroupDetailRepository;
import com.liyongjian.xhban.dal.AccountGroupFamilyRepository;
import com.liyongjian.xhban.dal.AccountGroupRepository;
import com.liyongjian.xhban.dal.BlogMediaRepository;
import com.liyongjian.xhban.dal.BlogRepository;
import com.liyongjian.xhban.dal.GroupMemberRepository;
import com.liyongjian.xhban.dal.GroupRepository;
import com.liyongjian.xhban.dal.UserFriendRepository;
import com.liyongjian.xhban.dal.UserMsgRepository;
import com.liyongjian.xhban.dal.UserRepository;
import com.liyongjian.xhban.dto.AjaxResponse;
import com.liyongjian.xhban.dto.SessionUser;
import com.liyongjian.xhban.model.AccountGroup;
import com.liyongjian.xhban.model.AccountGroupDetail;
import com.liyongjian.xhban.model.AccountGroupFamily;
import com.liyongjian.xhban.model.Blog;
import com.liyongjian.xhban.model.BlogMedia;
import com.liyongjian.xhban.model.Group;
import com.liyongjian.xhban.model.GroupMember;
import com.liyongjian.xhban.model.User;
import com.liyongjian.xhban.model.emumm.AccountGroupFamilyType;
import com.liyongjian.xhban.model.emumm.BlogType;
import com.liyongjian.xhban.model.emumm.LiveDieState;
import com.liyongjian.xhban.model.emumm.MediaType;
import com.liyongjian.xhban.model.emumm.VerifyState;
import com.liyongjian.xhban.utils.MapUtils;


@Controller
@RequestMapping("/api/group")
public class GroupController extends BaseController {

    @Autowired
    private UserMsgRepository userMsgRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private AccountGroupRepository accountGroupRepository;
    @Autowired
    private GroupRepository groupRepository;
    @Autowired
    private AccountGroupDetailRepository accountGroupDetailRepository;
    @Autowired
    private BlogRepository blogRepository;
    @Autowired
    private BlogMediaRepository blogMediaRepository;
    @Autowired
    private UserFriendRepository userFriendRepository;
    @Autowired
    private GroupMemberRepository groupMemberRepository;
    @Autowired
    private AccountGroupFamilyRepository accountGroupFamilyRepository;

    @ResponseBody
    @RequestMapping(path = "my/list", method = RequestMethod.GET)
    public AjaxResponse list(HttpServletRequest request, String token, HttpServletResponse response)
            throws Exception {
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = this.getCurrentUser(token);
        List<AccountGroup> list = accountGroupRepository.findAccountGroupByUserId(su.getId());
        List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>();
        for (AccountGroup ag : list) {
            Group g = groupRepository.findOne(ag.groupId);
            Map<String, Object> map = MapUtils.convert(g);
            map.put("photo", userRepository.findOne(g.updUserId).photo);
            map.put("isDefault", ag.isDefault);
            if (g.type == BlogType.HH) {
                map.put("balance", new BigDecimal(ag.payMoney - ag.money)
                        .setScale(2, RoundingMode.UP).floatValue());

                List<User> users = accountGroupRepository.findUserByGroupId(g.id);
                List<Map<String, Object>> userList = new ArrayList<Map<String, Object>>();
                for (User user : users) {
                    Map<String, Object> userMap =
                            MapUtils.convert(user, "id", "name", "nickName", "photo");
                    userList.add(userMap);
                }
                map.put("userList", userList);
            } else if (g.type == BlogType.JT) {
                List<GroupMember> gms =
                        groupMemberRepository.findByGroupIdAndState(g.id, LiveDieState.LIVE);
                map.put("gms", gms);
            }
            lists.add(map);
        }
        return ajax.setObj(lists);
    }



    @ResponseBody
    @RequestMapping(path = "member/add", method = RequestMethod.POST)
    public AjaxResponse list(HttpServletRequest request, String token, Long groupId, String name)
            throws Exception {
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = this.getCurrentUser(token);
        Group group = groupRepository.findOne(groupId);
        GroupMember gm = new GroupMember();
        gm.groupId = groupId;
        gm.name = name;
        gm.userId = su.id;
        gm.updUserId = group.updUserId;
        groupMemberRepository.save(gm);
        return ajax;
    }

    @Transactional
    @ResponseBody
    @RequestMapping(path = "detail/save", method = RequestMethod.POST)
    public AjaxResponse save(HttpServletRequest request, String token, Float money, String text,
            Long groupId, Long groupMemberId, AccountGroupFamilyType agfType, String imgUrls,
            String userIds) throws Exception {
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = this.getCurrentUser(token);
        accountGroupRepository.updateIsDefaultByUserId(su.getId());
        AccountGroup ag = accountGroupRepository.findByUserIdAndGroupIdAndState(su.id, groupId,
                LiveDieState.LIVE);
        ag.isDefault = true;
        accountGroupRepository.save(ag);

        Group group = groupRepository.findOne(groupId);

        Blog blog = new Blog();
        blog.text = text;
        blog.type = group.type;
        blog.userId = su.getId();
        blog.lookUserIds = userIds;
        blogRepository.save(blog);

        if (imgUrls != null) {
            String[] imgs = StringUtils.strip(imgUrls, ",").split(",");
            for (String imgUrl : imgs) {
                if (!StringUtils.isEmpty(imgUrl)) {
                    BlogMedia bm = new BlogMedia();
                    bm.url = imgUrl;
                    bm.blogId = blog.id;
                    bm.type = MediaType.PIC;
                    blogMediaRepository.save(bm);
                }
            }
        }


        if (group.type == BlogType.HH) {
            String[] ids = StringUtils.strip(userIds, ",").split(",");
            AccountGroupDetail agd = new AccountGroupDetail();
            agd.blogId = blog.id;
            agd.groupId = group.id;
            agd.money = money;
            agd.userId = su.getId();
            agd.updUserId = group.updUserId;
            agd.accountGroupId = group.id;
            agd.userIds = userIds;

            Float money2 = agd.money / ids.length;
            agd.userIdsCount = ids.length;
            agd.userIdsMoney = money2;
            if (agd.userId == agd.updUserId.longValue()) {
                agd.state = VerifyState.TG;
            } else {
                agd.state = VerifyState.DQR;
            }
            accountGroupDetailRepository.save(agd);

            if (agd.state == VerifyState.TG) {
                accountGroupRepository.updatePayMoneyByUserIdAndGroupId(agd.userId, agd.groupId,
                        agd.money);

                for (String userId : ids) {
                    if (!StringUtils.isEmpty(userId)) {
                        accountGroupRepository.updateMoneyByUserIdAndGroupId(Long.valueOf(userId),
                                agd.groupId, agd.userIdsMoney);
                    }
                }
            }
        } else if (group.type == BlogType.JT) {
            AccountGroupFamily agf = new AccountGroupFamily();
            agf.blogId = blog.id;
            agf.groupId = group.id;
            agf.groupMemberId = groupMemberId;
            agf.type = agfType;
            if (agf.type == AccountGroupFamilyType.XF || agf.type == AccountGroupFamilyType.FD
                    || agf.type == AccountGroupFamilyType.JDHK
                    || agf.type == AccountGroupFamilyType.QTZC) {
                agf.money = -money;
            } else {
                agf.money = money;
            }
            agf.userId = su.id;
            agf.updUserId = group.updUserId;
            accountGroupFamilyRepository.save(agf);
        }


        return ajax;
    }
}
